package com.lj.cloudDisk.controller;

import com.lj.cloudDisk.config.exception.SpaceException;
import com.lj.cloudDisk.pojo.File;
import com.lj.cloudDisk.service.FileService;
import com.lj.cloudDisk.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Api(value = "文件管理接口")
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Autowired
    FileService fileService;

    /**
     * 获取当前目录下的文件
     */
    @ApiOperation(value = "获取当前目录下的文件")
    @PostMapping("/getCurDirFiles/{id}")
    public R getCurDirFiles(@PathVariable String id, @RequestBody String userDir){
           log.debug("用户id:{}，当前所处目录：{}",id ,userDir);

        List<File> curDirFiles = null;
        try {
            curDirFiles = fileService.getCurDirFiles(id, userDir);
            return R.success().data("files",curDirFiles);
        } catch (Exception e) {
           throw new SpaceException(20001,"获取文件目录失败,未知错误");
        }

    }

    /**
     * 搜索文件
     */
    @ApiOperation("搜索文件")
    @PostMapping("/findFile/{memId}/{content}")
    public R findFile(@PathVariable String memId,@PathVariable String content){

        try {
            Map<String, Object> file = fileService.findFile(memId, content);
            return R.success().data(file);
        } catch (Exception e) {
            throw new SpaceException(20001,"搜索文件失败,未知错误");
        }

    }

    @ApiOperation("上传文件同步信息至数据库")
    @PostMapping("/addDbFile")
    public R addDbFile(@RequestBody File file){
        File fileDb = null;
        try {
            fileDb = fileService.addDbFile(file);
        } catch (Exception e) {
            throw new SpaceException(20001,"文件同步信息出错");
        }
        return R.success().data("file",fileDb);
    }

    @ApiOperation("更新文件信息")
    @PostMapping("/updateFile")
    public R updateFile(@RequestBody Map<String,Object> map){

        //文件id
        String id = (String) map.get("id");
        String rename = (String) map.get("name");


        log.debug("fileId:{}",id);
        log.debug("rename:{}",rename);

        try {
            fileService.updateFile(id,rename);
        }catch (Exception e){
            throw  new SpaceException(20001,"文件更新失败");
        }

        return  R.success();
   }

}
